package com.wyl.java.thread_.create_;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.*;

/**
 * 线程的创建
 * 方法三：实现Callable接口，重写call方法
 * 启动Callable常用有2种方法
 * 1.使用FutureTask做桥梁，然后在使用Thread去运行FutureTask（麻烦）
 * 2.使用线程池运行
 * @author 吴宇亮 on 2023/3/24 15:53
 */
public class CreateThread03 implements Callable<Object> {

    public static void main(String[] args) {
        FutureTask<Object> task1 = new FutureTask<>(new CreateThread03());
        FutureTask<Object> task2 = new FutureTask<>(new CreateThread03());
        // 使用FutureTask做桥梁，然后在使用Thread去运行FutureTask
//        new Thread(task1).start();
//        new Thread(task2).start();

        // 使用线程池去运行
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(task1);
        executorService.submit(task2);
        executorService.shutdown();
    }

    @Override
    public Object call() {
        for (int i = 0; i < 5; i++) {
            try {
                if (RandomUtil.randomBoolean()) {
                    Thread.sleep(RandomUtil.randomLong(500, 1200));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
        return null;
    }
}
